package service

import (
	"log"
	"time"
)

func (s *ServiceImp) runCheckPingPong() {
	ticker := time.NewTicker(s.PingPongInterval)
	defer ticker.Stop()
	for {
		select {
		case <-s.close:
			return
		case t := <-ticker.C:
			s.connTree.Scan(func(key string, value *Conn) bool {
				if value.LatestBeatTime.Before(t.Add(-s.PingPongInterval)) {
					log.Println("ping-pong timeout, close connection:", value.Conn)
					if err := value.Close(nil); err != nil {
						log.Println("close conn error:", err)
					}
				}
				if !value.IsAuthValid {
					if value.ConnectTime.Before(t.Add(-s.LoginTimeout)) {
						log.Println("login timeout, close connection:", value.Conn)
						if err := value.Close(nil); err != nil {
							log.Println("close conn error:", err)
						}
					}
				}
				return true
			})
		}
	}
}
